package com.detrum.myijkplayer.widget.media;

import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.detrum.sportcamera.R;
import com.detrum.sqlite.SqliteMediaOperation;
import com.detrum.utils.LogUtils;
import com.detrum.utils.MyMethod;

import java.util.Formatter;
import java.util.Locale;

/**
 * Created by abc on 2018/2/24.
 */

public class MyController extends LinearLayout implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, MyVideoCall {
    private MyPlayerControl mPlayer;
    private Context context;
    private LayoutInflater layoutInflater;
    private TextView total_time, current_time;
    private SeekBar seekBar;
    private Button capture;
    private StringBuilder mFormatBuilder;
    private Formatter mFormatter;
    private boolean isShowing;
    private ImageView videoPlay;
    private Handler handler = new Handler(Looper.getMainLooper());

    public MyController(@NonNull Context context) {
        super(context);
        initView(context);
    }

    public MyController(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public MyController(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public MyController(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView(context);
    }

    private void initView(Context context) {
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
        layoutInflater.inflate(R.layout.my_controller, this, true);
        mFormatBuilder = new StringBuilder();
        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        total_time = findViewById(R.id.total_time);
        current_time = findViewById(R.id.current_time);
        seekBar = findViewById(R.id.progress_sb);
        capture = findViewById(R.id.capture);
        capture.setOnClickListener(this);
        seekBar.setOnSeekBarChangeListener(this);
    }

    public void setImageView(ImageView video_iv) {
        videoPlay = video_iv;
    }

    public void setTotal_time() {
        total_time.setText(stringForTime(mPlayer.getDuration()));
    }

    public void setCurrent_time() {
        current_time.setText(stringForTime(mPlayer.getCurrentPosition()));
    }

    public void setProgress() {
        seekBar.setSecondaryProgress(mPlayer.getBufferPercentage() * 10);
        int duration = mPlayer.getDuration();
        int position = mPlayer.getCurrentPosition();
        seekBar.setProgress((int) (position * 1000L / duration));
    }

    @Override
    public void onClick(View v) {
        if (v == capture) {
            mPlayer.capture("Controller", new CaptureCall() {
                @Override
                public void capturePath(String path) {
                    LogUtils.e("截屏成功");
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            MyMethod.ShowDialog(context, R.string.captureSuccess);
                        }
                    });
                }
            });
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            long total = mPlayer.getDuration();
            long current = total * progress / 1000L;
            mPlayer.seekTo((int) current);
            if (current_time != null) {
                current_time.setText(stringForTime((int) current));
            }
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    private String stringForTime(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        mFormatBuilder.setLength(0);
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }

    public void start() {
        mPlayer.start(0);
    }

    public void pause() {
        mPlayer.pause();
    }

    public boolean isPlaying() {
        return mPlayer.isPlaying();
    }

    @Override
    public void hide() {
        setVisibility(View.GONE);
        if (videoPlay != null) {
            videoPlay.setVisibility(View.GONE);
        }
        isShowing = false;
    }

    @Override
    public boolean isShowing() {
        return isShowing;
    }

    @Override
    public void show() {
        setVisibility(View.VISIBLE);
        if (videoPlay != null && !mPlayer.isPlaying()) {
            videoPlay.setVisibility(View.VISIBLE);
        }
        isShowing = true;
    }

    @Override
    public void show(int timeout) {

    }

    @Override
    public void setVideoView(MyPlayerControl myController) {
        mPlayer = myController;
    }

    @Override
    public void setEnable(boolean isEnable) {
        if (isEnable) {
            videoPlay.setVisibility(View.GONE);
        } else {
            videoPlay.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void setTime() {
        setTotal_time();
        setCurrent_time();
        setProgress();

    }

    public interface MyPlayerControl {
        void start(int flag);

        void pause();

        int getDuration();

        int getCurrentPosition();

        void seekTo(int pos);

        boolean isPlaying();

        int getBufferPercentage();

        boolean canPause();

        void capture(String flag, CaptureCall captureCall);

        /**
         * Get the audio session id for the player used by this VideoView. This can be used to
         * apply audio effects to the audio track of a video.
         *
         * @return The audio session, or 0 if there was an error.
         */
        int getAudioSessionId();
    }
}
